use std::{fs::{self, File, OpenOptions}, io::{Error, ErrorKind, Read, Write}, path::Path};

use crate::error;

pub fn makesure_dir(path_str: &String) {
	let path = Path::new(path_str);
	match fs::create_dir_all(path) {
		Err(e) => if e.kind() != ErrorKind::AlreadyExists {
			error!(e);
		}, Ok(_) => {},
	};
}

#[allow(unused)]
pub fn file_exists(path_str: &String) -> bool {
	Path::new(path_str).is_file()
}

#[allow(unused)]
pub fn dir_exists(path_str: &String) -> bool {
	let path = Path::new(path_str);
	if !path.exists() {
		false
	} else {
		!path.is_file()
	}
}

#[allow(unused)]
pub fn append_file(path_str: &String, content: &String) -> Result<(), Error> {
	let file = OpenOptions::new()
		.write(true)
		.create(true)
		.append(true)
		.open(path_str);
	if file.is_err() { return Err(file.unwrap_err()) }
	let mut file = file.unwrap();
	file.write_all(content.as_bytes())
}

pub fn overwrite_file(path_str: &String, content: &String) -> Result<(), Error> {
	let file = OpenOptions::new()
		.write(true)
		.create(true)
		.open(path_str);
	if file.is_err() { return Err(file.unwrap_err()) }
	let mut file = file.unwrap();
	file.write_all(content.as_bytes())
}

pub fn read_all(path_str: &String) -> String {
	let file = File::open(path_str);
	if file.is_err() { return "".to_string(); }
	let mut file = file.unwrap();
	let mut content = String::new();
	match file.read_to_string(&mut content) {
		Err(_) => "".to_string(),
		Ok(_) => content,
	}
}
